//
//  PMineBusinessCardViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/23.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "PMineBusinessCardViewController.h"
#import "LYBusinessCardCell.h"
#import "MineBusinessCardModel.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "UIImage+Helper.h"
#import "PMineBusinessCardChangeBgViewController.h"

@interface PMineBusinessCardViewController ()<UITableViewDelegate, UITableViewDataSource, ShareViewDelegate>
{
    NSInteger page;
    NSString *total;
    
    ShareView *shareBgView;
    UIImage *shareImg;
}
@property (nonatomic, strong) MineBusinessCardModel *infoModel;
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation PMineBusinessCardViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"我的名片";
    page = 1;
    total = @"0";
    self.infoModel = [[MineBusinessCardModel alloc] init];
    self.infoModel.lists = [NSMutableArray arrayWithCapacity:0];
    
    [self initUI];
    [self loadData];
}
- (void)loadData {
    self.noDataView.hidden = YES;
    SVPHUDShow;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    dic = [UIToolsControl getPublicParameter];
    [dic setObject:[NSString stringWithFormat:@"%ld", (long)page] forKey:@"page"];
    [dic setObject:PageSize forKey:@"number"];
    
    [BaseNetManager requestWithMethod:POST path:Person_NameCardLists_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            self->total = [UIToolsControl dataAnalysis:responseObject[@"data"][@"total"]];
            if (self->page == 1) {
                MineBusinessCardBaseModel *model = [[MineBusinessCardBaseModel alloc] init];
                [model setValuesForKeysWithDictionary:responseObject[@"data"][@"mine"]];
                self.infoModel.mine = model;
            }
            for (NSDictionary *dic in responseObject[@"data"][@"lists"]) {
                MineBusinessCardBaseModel *model = [[MineBusinessCardBaseModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.infoModel.lists addObject:model];
            }
            [self.tableview.mj_footer endRefreshing];
            [self.tableview reloadData];
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError * _Nonnull error) {
        SVPHUDError(NetErrorAlertText);
        [self.noDataView vcNilStatusType:VCNilStatusTypeOfNoNet superView:self.view];
    }];
}
- (void)initUI {
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT- HeightOfStatusBarAndNavigationBar) style:UITableViewStyleGrouped];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.showsVerticalScrollIndicator = NO;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = COLOR_OF_WHITE;
    self.tableview.sectionIndexBackgroundColor = COLOR_OF_CLEAR;
    
    [self.tableview registerClass:[LYBusinessCardCell class] forCellReuseIdentifier:kCellIdentifier_LYBusinessCardCell];
    [self.view addSubview:self.tableview];
    
    __weak __typeof(self)weakSelf = self;
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self->page++;
        [weakSelf.tableview.mj_footer beginRefreshing];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf loadData];
        });
    }];
    
    shareBgView = [[ShareView alloc] initWithTarget:self];
    shareBgView.hidden = YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.infoModel && (self.infoModel.mine || self.infoModel.lists.count)) {
        return 2;
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.infoModel && (self.infoModel.mine || self.infoModel.lists.count)) {
        if (section) {
            return self.infoModel.lists.count;
        } else {
            return 1;
        }
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LYBusinessCardCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LYBusinessCardCell forIndexPath:indexPath];
    
    if (indexPath.section) {
        MineBusinessCardBaseModel *model = self.infoModel.lists[indexPath.row];
        [cell reloadDataForModel:model indexPath:indexPath];
    } else {
        MineBusinessCardBaseModel *model = self.infoModel.mine;
        [cell reloadDataForModel:model indexPath:indexPath];
    }
    
    __weak typeof(self) weakSelf = self;
    cell.block = ^(NSInteger index){
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (indexPath.section) { // 删除
            MineBusinessCardBaseModel *model = strongSelf.infoModel.lists[indexPath.row];
            [strongSelf buttonClickAtIndex:index indexPath:indexPath model:model];
        } else { // 分享
            MineBusinessCardBaseModel *model = strongSelf.infoModel.mine;
            [strongSelf buttonClickAtIndex:index indexPath:indexPath model:model];
        }
    };
    return cell;
}
#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = (WIDTH-40.0*Scale)*685/1005;
    return 60.0*Scale+height;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 15, WIDTH -30 , 30)];
    if (section == 0) {
        label.textColor = THEMECOLOR_OF_TEXT_666666;
        label.font = [UIFont systemFontOfSize:14];
        label.text = @"我的名片";
        
        UIButton *changeBgBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-90, 15, 80, 30) imageName:nil target:self action:@selector(changeBgBtnTap) title:@"名片换肤" titleColor:THEMECOLOR_OF_TEXT_666666];
        changeBgBtn.titleLabel.font = Font(14);
        [view addSubview:changeBgBtn];
    } else {
        label.textColor = THEMECOLOR_OF_TEXT_9a9a9a;
        label.font = [UIFont systemFontOfSize:13];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"我收藏的名片("];
        NSAttributedString *strq = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", total] attributes:@{NSForegroundColorAttributeName :[UIColor redColor],NSFontAttributeName : [UIFont systemFontOfSize:13]}];
        [str appendAttributedString:strq];
        NSAttributedString *strq1 = [[NSAttributedString alloc] initWithString:@")" attributes:@{NSForegroundColorAttributeName :THEMECOLOR_OF_TEXT_9a9a9a,NSFontAttributeName : [UIFont systemFontOfSize:13]}];
        [str appendAttributedString:strq1];
        label.attributedText = str;
    }
    [view addSubview:label];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001f;
}
- (void)changeBgBtnTap {
    __weak __typeof(self)weakSelf = self;
    PMineBusinessCardChangeBgViewController *VC = [[PMineBusinessCardChangeBgViewController alloc] init];
    VC.select = ^(BOOL selectFlag, NSString * _Nonnull skin_id, NSString * _Nonnull skin_img) {
        if (selectFlag) {
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            MineBusinessCardBaseModel *model = strongSelf.infoModel.mine;
            model.skin_id = skin_id;
            model.skin_img = skin_img;
            
            [strongSelf.tableview reloadSections:[[NSIndexSet alloc] initWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    };
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark -- Action
- (void)buttonClickAtIndex:(NSInteger)index indexPath:(NSIndexPath *)indexPath model:(MineBusinessCardBaseModel *)model {
    LYBusinessCardCell *cell = [self.tableview cellForRowAtIndexPath:indexPath];
    if (index == 0) { //保存
        UIImage *image = [UIToolsControl snapshot:cell.cardview];
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (error) {
                if (UD_GetOForK(isPhotoSuthorization)) { SVPHUDError(@"保存失败,请在设置中设置允许访问相册,以便保存名片");
                } else {
                    UD_SetOForK(isYes, isPhotoSuthorization);
                }
            } else {
                SVPHUDSuccess(@"保存成功");
            }
        }];
    } else {
        if (indexPath.section) { //删除
            SVPHUDShow;
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
            dic = [UIToolsControl getPublicParameter];
            [dic setObject:model.userid forKey:@"userid"];
            
            [BaseNetManager requestWithMethod:POST path:Person_NameCardDelete_URL params:dic successBlock:^(NSDictionary * _Nonnull responseObject) {
                if ([responseObject[@"code"] integerValue] == 2000) {
                    SVPHUDSuccess(responseObject[@"msg"]);
                    [self.infoModel.lists removeObjectAtIndex:indexPath.row];
                    [self.tableview reloadData];
//                    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section], nil] withRowAnimation:UITableViewRowAnimationNone];
                } else {
                    SVPHUDError(responseObject[@"msg"]);
                }
            } failurBlock:^(NSError * _Nonnull error) {
                SVPHUDError(NetErrorAlertText);
            }];
        } else { //分享
            if ([UIToolsControl canOpenWXApp]) {
                shareImg = [UIToolsControl snapshot:cell.cardview];
                shareBgView.hidden = NO;
            } else {
                SVPHUDError(@"请先安装微信App");
            }
        }
    }
}
- (void)shareViewCancel:(ShareView *)shareView {
    shareView.hidden = YES;
}
- (void)shareViewSelectItem:(ShareView *)shareView type:(ShareType)shareType {
    shareView.hidden = YES;
    switch (shareType) {
        case ShareTypeOfWXHaoyou: {
            [UIToolsControl wxShareImg:shareImg shareType:ShareTypeOfWXHaoyou];
        } break;
        case ShareTypeOfWXPengyouquan: {
            [UIToolsControl wxShareImg:shareImg shareType:ShareTypeOfWXPengyouquan];
        } break;
        case ShareTypeOfQQ: {
            [UIToolsControl qqShareImg:shareImg title:@"" desc:@"" shareType:ShareTypeOfQQ];
        } break;
        case ShareTypeOfQQZone: {
            [UIToolsControl qqShareImg:shareImg title:@"" desc:@"" shareType:ShareTypeOfQQZone];
        } break;
        default:
            break;
    }
}
//- (void)buttonClickAtIndex:(NSInteger)index indexPath:(NSIndexPath *)indexPath model:(LYBusinessCardModel *)model{
//    LYBusinessCardCell *cell = [self.tableview cellForRowAtIndexPath:indexPath];
//    if (index == 0) {
//        //保存
//        UIImage *image =[LYTool snapshot:cell.cardview];
//        [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
//
//            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
//
//        } completionHandler:^(BOOL success, NSError * _Nullable error) {
//            if (error) {
//                NSLog(@"%@",@"保存失败");
//            } else {
//                NSLog(@"%@",@"保存成功");
//            }
//        }];
//
//    }else{
//        if (model.type == 1) {
//            //公司 -- 删除
//
//        }else{
//            //个人 -- 分享
//
//        }
//    }
//}

@end
